﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using P2P.Main.Model;
using P2P.Main.Session;
using P2P.Network.ExtensionMethods;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace P2P.Main.Handler
{
    public class RegisterHandler
    {
        private ApiProtocol apiProtocol;

        public RegisterHandler(ApiProtocol apiProtocol)
        {
            this.apiProtocol = apiProtocol;
        }

        /// <summary>
        /// 注册Tcp穿透端口
        /// </summary>
        public void RegisterTcpPublicPort() 
        {
            string AccountId = (string)apiProtocol.Params["AccountId"];

            ActiveNode? activeNode = ActiveNodeSessionManager.Instance.Find(AccountId);

            if (activeNode == null)
            {
                return;
            }
            ActiveNodeSessionManager.Instance.Register(AccountId, apiProtocol.RemoteEndPoint.Port);

            JObject data = new JObject();
            data.Add("Name", "RegisterAck");
            data.Add("Method", "RegisterAck");
            data.Add("Version", "1.0");

            string ack = JsonConvert.SerializeObject(R<JObject>.Ok(data));
            apiProtocol.Socket.Send(ack);
        }
    }
}
